package org.bud.rung.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.bud.rung.bit.JobRequest;
import org.bud.rung.netty.coder.Decoder;
import org.bud.rung.netty.coder.Encoder;
import org.bud.rung.netty.server.ServerInHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author shaun
 * @date 2024/8/10
 * @instruction
 */
public class NettyClient {
    private static final NettyClient client = new NettyClient();
    private Channel channel;
    private final Object lock = new Object();
    private static volatile boolean first = true;
    public void start(){
        Bootstrap bootstrap = new Bootstrap();
        try {
            channel = bootstrap
                    .channel(NioSocketChannel.class)
                    .group(new NioEventLoopGroup())
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new Decoder())
                                    .addLast(new Encoder())
                                    .addLast(new ClientInHandler())
                                    .addLast(new ClientOutHandler());
                        }
                    })
                    .connect(new InetSocketAddress("localhost", 9996)).sync().channel();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void send(String jobName){
        this.channel.writeAndFlush(JobRequest.builder().jobName(jobName).build());
    }

    public static NettyClient getInstance(){
        return client;
    }
}
